<template>
  <div class='container'>
    <el-dialog
  :title="isEdit?'修改学科':'新增学科'"
  :visible="dialogVisible"
  width="40%"
  @close="closeDialog">
  <!-- 表单区域 -->
  <!-- <span>这是一段信息</span> -->
  <el-form ref="subjectRef" :model="subjectForm" :rules="subjectRules" label-width="80px">
    <el-form-item label="学科名称" prop="subjectName">
      <el-input placeholder="请输入学科名称" v-model="subjectForm.subjectName"></el-input>
    </el-form-item>
<el-form-item label="是否显示" prop="isFrontDisplay">
  <el-switch v-model="subjectForm.isFrontDisplay" :active-value="1" :inactive-value="0" active-color="green" inactive-color="red"></el-switch>
</el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="$emit('close-dialog')">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { add as addSubject, detail as detailSubject, update as updateSubject } from '@/api/hmmm/subjects'
export default {
  data () {
    return {
      // 表单数据对象
      subjectForm: {
        subjectName: '', // 学科名称
        isFrontDisplay: 1// 前台是否显示
      },
      // 表单验证规则对象
      subjectRules: {
        subjectName: [
          { required: true, message: '内容不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 10, message: '学校名称要求是1-10个字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    params: {
      type: Object
    }
  },
  methods: {
    // 点击X和蒙版关闭弹层
    closeDialog () {
      // 触发自定义组件，通知父组件关闭弹层
      this.$emit('close-dialog')
      // 弹窗关闭后清空表单内容
      this.$refs.subjectRef.resetFields()
      // 手动清空数据
      this.subjectForm = {
        subjectName: '',
        isFrontDisplay: 1
      }
    },
    // 点击确定，添加或者修改学科
    submit () {
      // 1.表单兜底校验
      this.$refs.subjectRef.validate(async valid => {
        if (!valid) return
        // 校验通过，调用接口
        if (this.isEdit) {
          // 修改操作
          await updateSubject({
            ...this.subjectForm
          })
        } else {
          // 添加操作
          await addSubject({
            subjectName: this.subjectForm.subjectName,
            isFrontDisplay: this.subjectForm.isFrontDisplay
          })
          this.params.page = 1
        }
        // 3.提示用户
        const msg = this.isEdit ? '修改学科成功' : '新增学科成功'
        this.$message.success(msg)
        // 4.关闭弹窗
        this.closeDialog()
        // 5.刷新学科列表
        this.$emit('get-subject-list')
      })
    },
    // 获取学科详情
    async getSubjectDetail (data) {
      const res = await detailSubject(data)
      this.subjectForm.subjectName = res.data.subjectName
      this.isFrontDisplay = res.data.isFrontDisplay
      this.subjectForm = res.data
    }
  }
}
</script>

<style scoped lang='less'></style>
